package com.newflypig.jblog.controller;

import java.sql.Timestamp;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.google.code.kaptcha.Constants;
import com.newflypig.jblog.exception.JblogException;
import com.newflypig.jblog.model.Article;
import com.newflypig.jblog.model.Comment;
import com.newflypig.jblog.service.CommentService;

@Controller
public class CommentController {
	@Resource(name="commentService")
	private CommentService commentService;
	
	@RequestMapping(value="/addComment",method=RequestMethod.POST)
	public String addComment(@ModelAttribute("comment") Comment comment,@RequestParam(value="articleId",required=true) Integer articleId,@RequestParam(value="captcha" ,required=true) String captcha,HttpSession session){
		if(articleId==null || captcha==null || "".equals(captcha))
			throw new JblogException("Illegal invasion,you must stop!");
		if(!session.getAttribute(Constants.KAPTCHA_SESSION_KEY).equals(captcha))
			throw new JblogException("Wrong Captcha,please try again.");
		if(comment.getText().length()>500)
			throw new JblogException("Comment's text too long,it must <=500 words.");
		if(!comment.getNickname().matches("\\w+@(\\w+.)+[a-z]{2,3}"))
			throw new JblogException("Email format is incorrect");
		comment.setArticle(new Article(articleId));
		comment.setDate(new Timestamp(new Date().getTime()));
		this.commentService.save(comment);
		return "redirect:/article/"+articleId+"/show";
	}
}
